<template>
  <view class="container">
    <transition name="fade">
      <view v-show="showSearch" class="search-section">
        <wd-card>
          <view class="search-form">
            <view class="form-row">
              <view class="form-item">
                <wd-badge :value="userSelectCount" :max="10">
                  <wd-button type="primary" @click="openUserSelect">选择申请人</wd-button>
                </wd-badge>
              </view>
              <view class="form-item">
                <text class="form-label">任务名称</text>
                <wd-input
                  v-model="queryParams.nodeName"
                  placeholder="请输入任务名称"
                  @confirm="handleQuery"
                />
              </view>
            </view>
            <view class="form-row">
              <view class="form-item">
                <text class="form-label">流程定义名称</text>
                <wd-input
                  v-model="queryParams.flowName"
                  placeholder="请输入流程定义名称"
                  @confirm="handleQuery"
                />
              </view>
              <view class="form-item">
                <text class="form-label">流程定义编码</text>
                <wd-input
                  v-model="queryParams.flowCode"
                  placeholder="请输入流程定义编码"
                  @confirm="handleQuery"
                />
              </view>
            </view>
            <view class="form-actions">
              <wd-button type="primary" @click="handleQuery">
                <wd-icon name="search"></wd-icon>
                搜索
              </wd-button>
              <wd-button @click="resetQuery">
                <wd-icon name="refresh"></wd-icon>
                重置
              </wd-button>
            </view>
          </view>
        </wd-card>
      </view>
    </transition>

    <wd-card class="table-card">
      <template #header>
        <view class="card-header">
          <right-toolbar v-model:show-search="showSearch" @query-table="handleQuery"></right-toolbar>
        </view>
      </template>
      <lh-table :rows="state.rows" :columns="state.columns" @tapRow=tapRow>
      </lh-table>

      <!-- 分页 -->
      <view v-show="total > 0" class="pagination-container">
        <pagination
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @pagination="handleQuery"
        />
      </view>
    </wd-card>

    <!-- 申请人选择 -->
    <UserSelectSingle
      ref="UserSelectSingleRef"
      v-model:visable="userselectvisable"
      @confirm-call-back="userSelectCallBack"
    ></UserSelectSingle>
  </view>
</template>

<script setup lang="ts">
import { getNextNodeList, pageByTaskFinish } from '@/pagesA/api/workflow/task';
import type { TaskQuery, FlowTaskVO } from '@/pagesA/api/workflow/task/types';
import workflowCommon from '@/pagesA/api/workflow/workflowCommon';
import type { RouterJumpVo } from '@/pagesA/api/workflow/workflowCommon/types';
//审批记录组件
const { wf_business_status } = toRefs<any>(useDict('wf_business_status'));
const { wf_task_status } = toRefs<any>(useDict('wf_task_status'));
import UserSelectSingle from '@/pagesA/components/UserSelectSingle/index.vue';
import { onMounted, reactive, ref, toRefs } from 'vue';
import type { UserVO } from '@/api/system/user/types';
import { cancelProcessApproval } from '@/pagesA/api/workflow/instance';
import { useUserStore } from '@/store/modules/user';
import { useDict } from '@/api/system/dict';
const userStore = useUserStore();
const UserSelectSingleRef = ref<InstanceType<typeof UserSelectSingle>>();
const userselectvisable = ref(false);

const state = reactive({
  columns: [
    {
      name: 'flowName',
      title: '流程定义名称',
      width: '20%',
    },
    {
      name: 'createByName',
      title: '申请人',
      width: '20%',
    },
    {
      name: 'nodeName',
      title: '任务名称',
      width: '20%',
    },
    {
      name: 'approveName',
      title: '办理人',
      width: '20%',
    },
    {
      name: 'flowStatus',
      title: '流程状态',
      width: '20%',
    },
    {
      name: 'flowTaskStatus',
      title: '任务状态',
      width: '20%',
    },
    {
      name: '1',
      title: '1',
    },
  ],
  rows : []
})
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<Array<any>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 模型定义表格数据
const taskList = ref([]);
// 查询参数
const queryParams = ref<TaskQuery>({
  pageNum: 1,
  pageSize: 100,
  nodeName: undefined,
  flowName: undefined,
  flowCode: undefined,
  createByIds: []
});
//申请人选择数量
const userSelectCount = ref(0);
const queryFormRef = ref();
/** 搜索按钮操作 */
const handleQuery = () => {
  getFinishList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 50;
  queryParams.value.createByIds = [];
  userSelectCount.value = 0;
  handleQuery();
};

const tapRow = (data) => {
    // console.log('tapRow 接收到的所有参数:', data);

    // // 尝试不同的参数解构方式
    // console.log('param1 (可能是 index):', data);
    // console.log('param2 (可能是 data):', data.data);
    // console.log('param2 (可能是 businessId):', data.data.businessId);
    workflowCommon.routerJumpFinsh({
        businessId: data.data.businessId,
        taskId: data.data.instanceId,
        approveName: data.data.approveName,
        type: 'finish',
        formCustom: data.data.formCustom,
        formPath: data.data.formPath,
        historyTaskId: data.data.id
    });
};
const getFinishList = () => {
  loading.value = true;


  pageByTaskFinish(queryParams.value).then((resp: any) => {

    // 兼容不同的响应结构
    taskList.value = resp.rows;
    total.value = resp.total || 0;
    console.log('设置后的 taskList.value 长度:',taskList.value?.length);
    state.rows = taskList.value;

    // 处理状态显示
    for(let i = 0; i < state.rows.length; i++) {
        state.rows[i].flowStatus = wf_business_status.value.find((item: any) => item.value === state.rows[i].flowStatus)?.label;
        state.rows[i].flowTaskStatus = wf_task_status.value.find((item: any) => item.value === state.rows[i].flowTaskStatus)?.label;
    }

    loading.value = false; // 移到这里
  }).catch((error) => {
    console.error("请求失败:", error);
    loading.value = false; // 错误时也要设置为 false
  });
};
//打开申请人选择
const openUserSelect = () => {
  userselectvisable.value = true;
};
//确认选择申请人
const userSelectCallBack = (data: UserVO) => {
  console.log('选择的用户数据:', data);

  if (data && data.userId) {
    // 确保传递的是数组格式，后端期望 List<Long>
    queryParams.value.createByIds = [Number(data.userId)];
    console.log('设置的查询参数 createByIds:', queryParams.value.createByIds);

    // 自动触发查询
    handleQuery();
  } else {
    // 清空筛选条件
    queryParams.value.createByIds = [];
    console.log('清空查询参数');
    handleQuery();
  }
};
onMounted(() => {
  getFinishList();
});
</script>

<style lang="scss" scoped>
.container {
  padding: 32rpx;
  background: #f5f7fa;
  min-height: 100vh;
}

.search-section {
  margin-bottom: 32rpx;
}

.search-form {
  padding: 32rpx;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
  margin-bottom: 24rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-item {
  flex: 1;
  min-width: 300rpx;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.form-label {
  font-size: 28rpx;
  color: #606266;
  font-weight: 500;
}

.form-actions {
  display: flex;
  gap: 24rpx;
  justify-content: flex-end;
  margin-top: 32rpx;

  .wd-button {
    display: flex;
    align-items: center;
    gap: 8rpx;
  }
}

.table-card {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
}

.card-header {
  padding: 32rpx;
  border-bottom: 1rpx solid #ebeef5;
}

.table-scroll {
  width: 100%;
  white-space: nowrap;
}

.table-container {
  min-width: 1200rpx;
}

.table-header,
.table-row {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #ebeef5;
}

.table-header {
  background: #f5f7fa;
  font-weight: 600;
  color: #606266;
  height: 88rpx;
}

.table-row {
  height: 96rpx;
  transition: background-color 0.3s ease;

  &:hover {
    background: #f5f7fa;
  }

  &.selected {
    background: #ecf5ff;
  }

  &:last-child {
    border-bottom: none;
  }
}

.table-cell {
  padding: 0 24rpx;
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #606266;
  flex: 1;
  min-width: 0;

  &.selection-cell {
    flex: 0 0 80rpx;
    justify-content: center;
  }

  &.index-cell {
    flex: 0 0 100rpx;
    justify-content: center;
    font-weight: 500;
  }

  &.version-cell {
    flex: 0 0 120rpx;
    justify-content: center;
  }

  &.status-cell {
    flex: 0 0 140rpx;
    justify-content: center;
  }

  &.action-cell {
    flex: 0 0 200rpx;
    justify-content: center;
  }
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.pagination-container {
  padding: 32rpx;
  border-top: 1rpx solid #ebeef5;
  display: flex;
  justify-content: center;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .container {
    padding: 24rpx;
  }

  .form-row {
    flex-direction: column;
    gap: 16rpx;
  }

  .form-item {
    min-width: auto;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .table-container {
    min-width: 800rpx;
  }

  .table-cell {
    font-size: 26rpx;
    padding: 0 16rpx;
  }

  .action-buttons {
    flex-direction: column;
    gap: 8rpx;
  }
}
</style>
